package com.gmlive.common.upload.plugin;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.google.gson.Gson;
import com.taobao.api.ApiException;

import org.gradle.api.Action;
import org.gradle.api.DefaultTask;
import org.gradle.api.Project;
import org.gradle.api.tasks.TaskAction;
import org.gradle.api.tasks.util.PatternFilterable;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @作者: 姜志敏
 * @日期: 2020-01-04
 */
public class DingTalkTask extends DefaultTask {

    @TaskAction
    public void sendDingTalk() {
        //sendActionMessageToDingTalk();
//        sendActionMessage();
        DingTalkUtil.INSTANCE.testMD5(getProject());

        Project project = getProject();
        project.fileTree(project.getBuildDir() + "outputs/apk").matching(
                new Action<PatternFilterable>() {
                    @Override
                    public void execute(PatternFilterable patternFilterable) {
                        patternFilterable.exclude(".apk");
                    }
                });
    }

    private void sendActionMessageToDingTalk() {
        DingTalkClient client = new DefaultDingTalkClient(Constants.YINPAO_ROBOT_URL);
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        request.setMsgtype("actionCard");
        OapiRobotSendRequest.Actioncard actionCard = new OapiRobotSendRequest.Actioncard();
        actionCard.setTitle("[SDK助手提示]打包消息");

        OapiRobotSendRequest.Btns leftButton = new OapiRobotSendRequest.Btns();
        leftButton.setTitle("下载APK");
        OapiRobotSendRequest.Btns rightButton = new OapiRobotSendRequest.Btns();
        rightButton.setTitle("变更记录");
        List<OapiRobotSendRequest.Btns> buttons = new ArrayList<>();
        buttons.add(leftButton);
        buttons.add(rightButton);
        actionCard.setBtns(buttons);
        actionCard.setBtnOrientation("1");

        actionCard.setText(buildActionMsgText());
        request.setActionCard(actionCard);

//        OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
//        List<String> mobiles = new ArrayList<>();
//        mobiles.add("13798076537");
//        at.setAtMobiles(mobiles);
        request.setAt(buildAtString());

        try {
            OapiRobotSendResponse response = client.execute(request);
        } catch (ApiException e) {
            e.printStackTrace();

            System.out.println(e.getMessage());
        }
    }

    private void sendActionMessage() {
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8"),
                buildActionString());

        Request request = new Request.Builder()
                .url("https://oapi.dingtalk.com/robot/send?access_token=a6c8970ffa88fa607adb7a3cf0991eb5ef88831c0184cd9f459ff3267ea7de8e")
                .post(requestBody)
                .build();

        try {
            Response response = client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String buildActionMsgText() {
        StringBuilder sb = new StringBuilder();
        sb.append("Someone").append("\n");
        sb.append("------").append("\n");

        sb.append("- 任务: #9").append("\n");
        sb.append("- 执行人：姜志敏").append("\n");
        sb.append("- mapping: ").append("\n");
        return sb.toString();
    }

    private String buildActionString() {
        MessageModel message = new MessageModel();
        message.msgtype = "actionCard";
        MessageModel.Action action = new MessageModel.Action();
        action.title = "[SDK助手提示]";
        action.text = buildActionMsgText();

        List<MessageModel.ActionButton> buttons = new ArrayList<>();
        MessageModel.ActionButton button1 = new MessageModel.ActionButton();
        button1.title = "左边按钮";
        button1.actionURL = "https://www.baidu.com";
        MessageModel.ActionButton button2 = new MessageModel.ActionButton();
        button2.title = "右边按钮";
        button2.actionURL = "https://www.baidu.com";

        buttons.add(button1);
        buttons.add(button2);
        action.btns = buttons;

        message.actionCard = action;
        return new Gson().toJson(message);
    }

    private String buildAtString() {
        DingTalkAt at = new DingTalkAt();
        List<String> mobiles = new ArrayList<>();
        mobiles.add("13798076537");
        at.isAtAll = false;
        at.atMobiles = mobiles;

        return new Gson().toJson(at);
    }
}
